<?php
/**
 * @package Bike
 * @subpackage Ajax
 */

/**
 * Class for handling nested sets tree storages
 * @author Chrome
 * @package Bike
 * @subpackage Ajax
 */
class Bike_Ajax_TreeHandler extends Bike_Ajax_BaseHandler {
	
	/**
	 * Storage for handling
	 * @var Bike_Storage_Tree_NestedSets
	 */
	protected $storage = null;

	/**
	 * Constructor
	 * @param Bike_Storage_Tree_NestedSets $storage
	 */
	public function __construct(Bike_Storage_Tree_NestedSets $storage){
		$this->storage = $storage;
	}
	
	
	/**
	 * @see Bike_Ajax_BaseHandler::getStorage()
	 * @return Bike_Storage_IBase
	 */
	public function getStorage(){
		return $this->storage;
	}

	/**
	 * @see Bike_Ajax_IHandler::handle()
	 * @return array
	 */
	public function handle(Bike_IRequest $request){
		$operation = $request->getRequestVar('operation');
		$opResult = false;
		switch ($operation){
			case 'update':
				$nodeId = $request->getPostVar('nodeId');
				if(!empty($nodeId)){
					$data = $request->getPostVars();
					$opResult = $this->storage->updateNode($nodeId, $data);
				}
				$result = array('success' => $opResult, 'msg' => 'Record updated');
				break;
			case 'insert':
				$parentNodeId = $request->getPostVar('parentNodeId');
				if(!empty($parentNodeId)){
					$data = $request->getPostVars();
					$opResult = $this->storage->insertNode($parentNodeId, $data);
				}
				$result = array('success' => $opResult, 'msg' => 'Record added');
				break;
			case 'delete':
				$nodeId = $request->getPostVar('nodeId');
				if(!empty($nodeId)){
					$opResult = $this->storage->dropNode($nodeId);
				}
				$result = array('success' => $opResult, 'msg' => 'Record deleted');
				break;
			case null:
				$nodeData = $this->storage->getNodeById($request->getPostVar('node'));
				$result = $this->storage->getChildren($nodeData, true);
				$config = Bike_Service_Locator::getService('Config');
				$env = Bike_Service_Locator::getService('Environment');
				foreach($result as &$value){
					$value['leaf'] = ($value['right_key'] == ($value['left_key'] + 1));
					$value['text'] = $value['title'];
					$value['href'] = str_replace('/' . $config->getValue(array('sites', $env->getSiteName())) . '/', '/' ,$value['uri']);
				}
				break;
		}
		return $result;
	}
}
